# -*- coding: UTF-8 -*- #
"""
-------真正的勇士， 敢于直面惨淡的Warning、 敢于正视淋漓的Error-----
@author : 贾鹏博
@file : 14、接口自动化之文件上传.py
@time : 2022/5/16 8:54
"""

# ===========================    文件上传接口场景  ============================================
"""
解决接口测试流程中文件上传的问题
    指定 name ，同时也可做为校验   name="hogwarts_file"
    指定 filename , filename="hogwarts.txt"
    指定 content-type , multipart/form-data
"""

import requests

# 抓包工具中 ： Content-Disposition: form-data; name="hogwarts_file"; filename="1.txt"
r = requests.post('https://httpbin.ceshiren.com/post',
                  # files 参数用来解决文件上传接口
                  files={"hogwarts_file": open("./1.txt", "rb")},
                  proxies={"http": "http://127.0.0.1:8080",
                           "https": "http://127.0.0.1:8080"},
                  verify=False
                  )
"""
{
  "args": {}, 
  "data": "", 
  "files": {
    "hogwarts_file": "malasong"
  }, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate, br", 
    "Content-Length": "158", 
    "Content-Type": "multipart/form-data; boundary=0d447e979dfa622518f58e4548414cfa", 
    "Host": "httpbin.ceshiren.com", 
    "User-Agent": "python-requests/2.28.1", 
    "X-Forwarded-Host": "httpbin.ceshiren.com", 
    "X-Forwarded-Scheme": "https", 
    "X-Scheme": "https"
  }, 
  "json": null, 
  "origin": "111.18.44.195", 
  "url": "https://httpbin.ceshiren.com/post"
}

"""
print(r.text)
# 请求头断言
assert r.json()['headers']['Content-Type'].split(';')[0] == 'multipart/form-data'
# 内容断言
assert r.json()['files']['hogwarts_file'] == 'malasong'

# value 通过元组传递，实现指定 filename 的需求
# 抓包工具中 ： Content-Disposition: form-data; name="hogwarts_file"; filename="hogwarts.txt"
r = requests.post('https://httpbin.ceshiren.com/post',
                  # files 参数用来解决文件上传接口
                  files={"hogwarts_file": ("hogwarts.txt", open("./1.txt", "rb"))},
                  proxies={"http": "http://127.0.0.1:8080",
                           "https": "http://127.0.0.1:8080"},
                  verify=False
                  )

"""
{
  "args": {}, 
  "data": "", 
  "files": {
    "hogwarts_file": "malasong"
  }, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate, br", 
    "Content-Length": "165", 
    "Content-Type": "multipart/form-data; boundary=c72bb900e9f07505444df7ad1bc6cc13", 
    "Host": "httpbin.ceshiren.com", 
    "User-Agent": "python-requests/2.28.1", 
    "X-Forwarded-Host": "httpbin.ceshiren.com", 
    "X-Forwarded-Scheme": "https", 
    "X-Scheme": "https"
  }, 
  "json": null, 
  "origin": "111.18.44.195", 
  "url": "https://httpbin.ceshiren.com/post"
}


"""
print(r.text)
# 请求头断言
assert r.json()['headers']['Content-Type'].split(';')[0] == 'multipart/form-data'
# 内容断言
assert r.json()['files']['hogwarts_file'] == 'malasong'
